<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { useBoolean } from '@sa/hooks';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { fetchAddRole, fetchUpdateRole } from '@/service/api';
import { $t } from '@/locales';
import { enableStatusOptions } from '@/constants/business';
import MenuAuthModal from './menu-auth-modal.vue';
import ButtonAuthModal from './button-auth-modal.vue';

defineOptions({
  name: 'RoleOperateModal'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.Role | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();
const { bool: menuAuthVisible, setTrue: openMenuAuthModal } = useBoolean();
const { bool: buttonAuthVisible, setTrue: openButtonAuthModal } = useBoolean();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.manage.role.addRole'),
    edit: $t('page.manage.role.editRole')
  };
  return titles[props.operateType];
});

type Model = Pick<Api.SystemManage.Role, 'roleId' | 'roleName' | 'roleKey' | 'roleDesc' | 'status'>;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    roleId: 0,
    roleName: '',
    roleKey: '',
    roleDesc: '',
    status: null
  };
}

type RuleKey = Exclude<keyof Model, 'roleDesc' | 'roleId'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  roleName: defaultRequiredRule,
  roleKey: defaultRequiredRule,
  status: defaultRequiredRule
};

const roleId = computed(() => {
  if (props.operateType === 'edit' && props.rowData?.roleId) {
    return props.rowData.roleId;
  }
  return model.roleId || -1;
});

const isEdit = computed(() => props.operateType === 'edit');

function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.rowData) {
    // 确保 roleId 被正确设置
    Object.assign(model, props.rowData);
    if (props.rowData.roleId) {
      model.roleId = props.rowData.roleId;
    }
  }
}

function closeModal() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  try {
    let result;
    if (props.operateType === 'add') {
      result = await fetchAddRole(model as Api.SystemManage.Role);
    } else {
      result = await fetchUpdateRole(model as Api.SystemManage.Role);
    }

    if (!result.error) {
      const successMessage = props.operateType === 'add' ? $t('common.addSuccess') : $t('common.updateSuccess');
      window.$message?.success(successMessage);
      closeModal();
      emit('submitted');
    } else {
      window.$message?.error(result.error.message || $t('common.operationFailed'));
    }
  } catch (error) {
    console.error('Role operation failed:', error);
    window.$message?.error($t('common.operationFailed'));
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NModal v-model:show="visible" preset="dialog" :title="title" style="width: 600px; max-width: 90vw">
    <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="120">
      <NGrid :cols="2" :x-gap="16">
        <NFormItemGi v-if="isEdit" :label="$t('page.manage.role.roleId')" path="roleId">
          <NInput :value="String(roleId)" disabled />
        </NFormItemGi>
        <NFormItemGi :label="$t('page.manage.role.roleName')" path="roleName">
          <NInput v-model:value="model.roleName" :placeholder="$t('page.manage.role.form.roleName')" />
        </NFormItemGi>
        <NFormItemGi :label="$t('page.manage.role.roleKey')" path="roleKey">
          <NInput v-model:value="model.roleKey" :placeholder="$t('page.manage.role.form.roleKey')" />
        </NFormItemGi>
        <NFormItemGi :label="$t('page.manage.role.roleStatus')" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItemGi>
        <NFormItemGi :span="2" :label="$t('page.manage.role.roleDesc')" path="roleDesc">
          <NInput
            v-model:value="model.roleDesc"
            type="textarea"
            :placeholder="$t('page.manage.role.form.roleDesc')"
            :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </NFormItemGi>
      </NGrid>
    </NForm>

    <NSpace v-if="isEdit" class="mt-16px">
      <NButton @click="openMenuAuthModal">{{ $t('page.manage.role.menuAuth') }}</NButton>
      <MenuAuthModal v-model:visible="menuAuthVisible" :role-id="roleId" />
      <NButton @click="openButtonAuthModal">{{ $t('page.manage.role.buttonAuth') }}</NButton>
      <ButtonAuthModal v-model:visible="buttonAuthVisible" :role-id="roleId" />
    </NSpace>

    <template #action>
      <NSpace>
        <NButton @click="closeModal">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
